package com.panshi.controller.article;

import com.alibaba.fastjson.JSON;
import com.panshi.api.*;
import com.panshi.po.*;
import com.panshi.vo.*;
import com.panshi.pagevo.PageBeanVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@Controller
@Slf4j
public class Into {

    @Resource
    private ArticleApi articleApi;

    @Resource
    private UserApi userApi;

    @Resource
    private SortApi sortApi;

    @Resource
    private HttpServletRequest request;

    @Resource
    private IDiscussApi iDiscussApi;

    @Resource
    private PraiseApi praiseApi;

    @Resource
    private CollectApi collectApi;


    //详情
    @GetMapping("/detail/{number}")
    public ModelAndView detail(@PathVariable Integer number){
        //request.getSession();

        UserPO logicUser = findByEmail();

        ModelAndView mv = new ModelAndView("article/detail");

        ArticleNumberQueryVo queryVo = new ArticleNumberQueryVo();
        queryVo.setNumber(number);
        ResponseVO<ArticlePo> vo = articleApi.numberQuery(queryVo);
        ArticlePo po = vo.getData();

        //查询所有数据（推荐），下架的除外
        PageBeanVo page = new PageBeanVo();
        page.setCurrentPage(1);
        page.setPageSize(8);
        ResponseVO<List<ArticlePo>> res = articleApi.soldQuery(page);
        List<ArticlePo> data = res.getData();

        log.info("po========================={}",po);

        //用户信息（作者）
        UserPO user = userApi.findUserById(po.getUid()).getData();

        //相关推荐
        ArticleSortNameCountQueryVo sort = new ArticleSortNameCountQueryVo();
        sort.setSortname(po.getSortname());
        List<ArticlePo> correlationList = articleApi.sortQueryContent(sort).getData();

        //分类
        List<SortPO> sortList = sortApi.totalQuery().getData();

        //查询评论的参数
        QueryFidesVO queryFidesVO = new QueryFidesVO();
        queryFidesVO.setNid(po.getId());
        queryFidesVO.setTypees(0);
        queryFidesVO.setCurrentPage(1);
        queryFidesVO.setPageSize(10);

        //判断该用户是否已经收藏过这篇文章
        CollectGroupQueryVo groupQueryVo  =  new CollectGroupQueryVo();
        if(logicUser != null){
            groupQueryVo.setUid(logicUser.getId());
            groupQueryVo.setNid(po.getId());
            groupQueryVo.setType(0);
            CollectPo iscollect = collectApi.groupQuery(groupQueryVo).getData();

            log.info("*************************iscollect:{}",iscollect);

            if(null == iscollect){
                mv.addObject("iscollect",111);
            }
        }else{
            mv.addObject("iscollect",111);
        }

        //判断该用户是否已经点赞过了
        PraiseQueryVO praiseQueryVO = new PraiseQueryVO();
        praiseQueryVO.setNewsid(po.getId());
        praiseQueryVO.setSort(-1);
        praiseQueryVO.setType(0);


        //文章的评论
        List<DiscussPO> discussPO = iDiscussApi.queryFidDiscussPostBody(queryFidesVO).getData();
        //List<DiscussPO> discussPO = iDiscussApi.queryNidDiscussPostBody(queryNidVO).getData();

        //iDiscussApi.queryFidDiscussPostBody();

        log.info("评论================================={}",discussPO);

        List<UserDiscussVO> userDiscussVOS = new ArrayList<>();
        for (DiscussPO discuss:discussPO) {
            UserDiscussVO discussVO = new UserDiscussVO();
            BeanUtils.copyProperties(discuss,discussVO);

            if(logicUser != null){
                praiseQueryVO.setUid(logicUser.getId());
                praiseQueryVO.setDid(discuss.getId());
                PraisePO praisePO = praiseApi.findPraise(praiseQueryVO).getData();
                if(praisePO != null){
                    discussVO.setIslike(100);
                }
            }

            UserPO users = userApi.findUserById(discuss.getUid()).getData();
            discussVO.setUserPO(users);
            userDiscussVOS.add(discussVO);
        }


        log.info("***************************userDiscussVOS:{}",userDiscussVOS);
        mv.addObject("discusses",userDiscussVOS);
        mv.addObject("corr",correlationList);
        mv.addObject("zxuser",user);
        mv.addObject("sortList",sortList);
        mv.addObject("data",data);
        mv.addObject("article",po);
        mv.addObject("sortname",po.getSortname());
        mv.addObject("logicUser",logicUser);
        return mv;
    }

    @PostMapping("/moreDiscuss")
    public ModelAndView moreDiscuss(QueryFidesVO queryFidesVO){
        ModelAndView mav = new ModelAndView("article/detail-data");
        UserPO logicUser = findByEmail();

        queryFidesVO.setPageSize(10);

        log.info("queryFidesVO-----------------{}",queryFidesVO);

        List<DiscussPO> discussPO = iDiscussApi.queryFidDiscussPostBody(queryFidesVO).getData();

        //判断该用户是否已经点赞过了
        PraiseQueryVO praiseQueryVO = new PraiseQueryVO();
        praiseQueryVO.setNewsid(queryFidesVO.getNid());
        praiseQueryVO.setSort(-1);
        praiseQueryVO.setType(0);

        List<UserDiscussVO> userDiscussVOS = new ArrayList<>();
        for (DiscussPO discuss:discussPO) {
            UserDiscussVO discussVO = new UserDiscussVO();
            BeanUtils.copyProperties(discuss,discussVO);

            if(logicUser != null){
                praiseQueryVO.setUid(logicUser.getId());
                praiseQueryVO.setDid(discuss.getId());
                PraisePO praisePO = praiseApi.findPraise(praiseQueryVO).getData();
                if(praisePO != null){
                    discussVO.setIslike(100);
                }
            }
            UserPO users = userApi.findUserById(discuss.getUid()).getData();
            discussVO.setUserPO(users);
            userDiscussVOS.add(discussVO);
        }
        mav.addObject("logicUser",logicUser);
        mav.addObject("discusses",userDiscussVOS);
        return mav;
    }

    @PostMapping("/addCollect")
    @ResponseBody
    public Map<String,Object> addCollect(CollectAddVo collectAddVo){
        request.getSession();

        UserPO user = findByEmail();

        Map<String,Object> map = new HashMap<>();

        collectAddVo.setUid(user.getId());

        log.info("-----------------------collectAddVo:{}",collectAddVo);

        //判断该用户是否已经收藏过这篇文章
        CollectGroupQueryVo groupQueryVo  =  new CollectGroupQueryVo();
        groupQueryVo.setNid(collectAddVo.getNid());
        groupQueryVo.setUid(user.getId());//通过session域中的邮箱ID获取
        groupQueryVo.setType(collectAddVo.getType());
        CollectPo iscollect = collectApi.groupQuery(groupQueryVo).getData();

        log.info("===============================iscollect:{}",iscollect);

        if(null != iscollect){
            map.put("success",false);
            map.put("message","您已收藏了该文章了");
            return map;
        }

        Integer integer = collectApi.addCollect(collectAddVo).getData();
        if(integer == 0){
            map.put("success",false);
            map.put("message","抱歉，当前网络状况太差，请稍后再试");
        }else{
            //新增文章的收藏数
            ArticleUpdateVo updateVo = new ArticleUpdateVo();
            updateVo.setCollects(1);
            updateVo.setId(collectAddVo.getNid());

            Integer coll = articleApi.updateArticle(updateVo).getData();

            if(coll == 1){
                log.info("---------------------文章收藏成功");
            }

            map.put("success",true);
            map.put("message","收藏成功");
        }

        return map;
    }


    //根据父id查询
    @PostMapping("/findDiscussByFid")
    @ResponseBody
    public ModelAndView findDiscuss(QueryFidVO queryFidVO){
        ModelAndView mav = new ModelAndView("article/detail-data");

        UserPO logicUser = findByEmail();

        log.info("queryFidVO======================={}",queryFidVO);

        List<DiscussPO> list = iDiscussApi.queryFidesDiscussPostBody(queryFidVO).getData();

        log.info("*******************************list:{}",list);

        List<UserDiscussVO> disList = new ArrayList<>();
        for (DiscussPO po:list) {
            UserDiscussVO vo = new UserDiscussVO();
            BeanUtils.copyProperties(po,vo);



            UserPO userPO = userApi.findUserById(po.getUid()).getData();
            vo.setUserPO(userPO);

            //判断该用户是否已经点赞过了
            if(logicUser != null){
                PraiseQueryVO praiseQueryVO = new PraiseQueryVO();
                praiseQueryVO.setNewsid(po.getNid());
                praiseQueryVO.setSort(-1);
                praiseQueryVO.setType(0);
                praiseQueryVO.setUid(logicUser.getId());
                praiseQueryVO.setDid(po.getId());
                PraisePO praisePO = praiseApi.findPraise(praiseQueryVO).getData();
                if(praisePO != null){
                    vo.setIslike(100);
                }
            }

            disList.add(vo);
        }

        log.info("根据父id、nid、类型查找的评论数据：disList============{}",disList);

        mav.addObject("discussList",disList);


        return mav;
    }

    //增加评论
    @PostMapping("/addDiscuss")
    @ResponseBody
    public Map<String,Object> addDiscuss(AddDiscussVO addDiscussVO){

        UserPO user = findByEmail();

        addDiscussVO.setCreatedate(new Date());
        addDiscussVO.setUid(user.getId());
        addDiscussVO.setDates(new Date());

        log.info("addDiscussVO-----------------------{}",addDiscussVO);

        Map<String,Object> map = new HashMap<>();
        Integer isadd = iDiscussApi.addDiscussPostBody(addDiscussVO).getData();

        if(isadd == 0){
            map.put("message","当前网络状况较差，请稍后再试");
            map.put("success",false);
        }else{
            if(addDiscussVO.getFid() == null){
                //新增文章的评论数
                ArticleUpdateVo updateVo = new ArticleUpdateVo();
                updateVo.setComments(1);
                updateVo.setId(addDiscussVO.getNid());
                Integer isDiscuss = articleApi.updateArticle(updateVo).getData();
                if(isDiscuss == 1){
                    log.info("-----------------新增评论成功");
                }
            }else{
                //新增评论的回复数
                iDiscussApi.countReply(addDiscussVO.getFid()).getData();
            }

            map.put("message","评论成功");
            map.put("success",true);
        }

        return map;
    }

    @PostMapping("/addlike")
    @ResponseBody
    public String addlike(PraiseAddVO praiseAddVO) {

        UserPO user = findByEmail();
        praiseAddVO.setSort(-1);
        praiseAddVO.setType(0);
        praiseAddVO.setUid(user.getId());

        PraiseQueryVO queryVO = new PraiseQueryVO();
        BeanUtils.copyProperties(praiseAddVO,queryVO);

        PraisePO praisePO = praiseApi.findPraise(queryVO).getData();
        if(praisePO != null){
            return "您已经点赞过该评论了";
        }

        log.info("----------------------------praiseAddVO{}",praiseAddVO);

        Integer integer = praiseApi.praiseAdd(praiseAddVO).getData();

        Integer like = iDiscussApi.countTags(praiseAddVO.getDid()).getData();

        if(like == 0){
            log.info("------------------------对该评论进行点赞是否失败");
        }

        log.info("对该评论进行点赞是否成功=================={}",like);

        if(integer == 0){
            return "抱歉，网络状况较差，请稍后再进行操作";
        }
        return "点赞成功";
    }

    @PostMapping("/type")
    @ResponseBody
    public ModelAndView infor(@RequestParam Integer type){
        ModelAndView mv = new ModelAndView("article/information_data");
        //获取所有数据（推荐），下架的除外
        PageBeanVo pageBeanVo = new PageBeanVo();
        pageBeanVo.setCurrentPage(1);
        pageBeanVo.setPageSize(10);
        ResponseVO<List<ArticlePo>> vo = null;
        if(type == 10){//推荐
            vo = articleApi.soldQuery(pageBeanVo);
        }else if(type==15){//热门
            vo = articleApi.pvLimitQuery(pageBeanVo);
        }else if(type==20){//最新
            vo = articleApi.timeLimtQuery(pageBeanVo);
        }
        List<ArticlePo> article = vo.getData();

        List<InformationVO> list = new ArrayList<>();

        for (ArticlePo po:article) {
            InformationVO informationVO = new InformationVO();
            BeanUtils.copyProperties(po,informationVO);

            ResponseVO<UserPO> userResponse = userApi.findUserById(po.getUid());
            UserPO userPO = userResponse.getData();

            informationVO.setUser(userPO);

            list.add(informationVO);
        }
        log.info("--------------------------article:{}",list);

        mv.addObject("list",list);
        return mv;
    }

    @PostMapping("/load")
    @ResponseBody
    public ModelAndView infor(@RequestParam Integer type,@RequestParam Integer page){
        ModelAndView mv = new ModelAndView("article/information_data");
        //获取所有数据（推荐），下架的除外
        PageBeanVo pageBeanVo = new PageBeanVo();
        pageBeanVo.setCurrentPage(page);
        pageBeanVo.setPageSize(10);
        ResponseVO<List<ArticlePo>> vo = null;
        if(type == 10){//推荐
            vo = articleApi.soldQuery(pageBeanVo);
        }else if(type==15){//热门
            vo = articleApi.pvLimitQuery(pageBeanVo);
        }else if(type==20){//最新
            vo = articleApi.timeLimtQuery(pageBeanVo);
        }
        List<ArticlePo> article = JSON.parseArray(JSON.toJSONString(vo.getData()),ArticlePo.class);

        List<InformationVO> list = new ArrayList<>();

        for (ArticlePo po:article) {
            InformationVO informationVO = new InformationVO();
            BeanUtils.copyProperties(po,informationVO);

            ResponseVO<UserPO> userResponse = userApi.findUserById(po.getUid());
            UserPO userPO = JSON.parseObject(JSON.toJSONString(userResponse.getData()),UserPO.class);

            informationVO.setUser(userPO);

            list.add(informationVO);
        }
        log.info("--------------------------article:{}",article);

        mv.addObject("list",list);
        return mv;
    }

    //资讯 已解决
    @GetMapping("/information")
    public ModelAndView information(){
        ModelAndView mv = new ModelAndView("article/information");

        UserPO logicUser = findByEmail();

        //获取所有数据（推荐），下架的除外
        PageBeanVo pageBeanVo = new PageBeanVo();
        pageBeanVo.setCurrentPage(1);
        pageBeanVo.setPageSize(10);
        ResponseVO<List<ArticlePo>> vo = articleApi.soldQuery(pageBeanVo);
        List<ArticlePo> article = vo.getData();

        List<InformationVO> list = new ArrayList<>();

        for (ArticlePo po:article) {
            InformationVO informationVO = new InformationVO();
            BeanUtils.copyProperties(po,informationVO);

            ResponseVO<UserPO> userResponse = userApi.findUserById(po.getUid());
            UserPO userPO = userResponse.getData();

            informationVO.setUser(userPO);

            list.add(informationVO);
        }

        log.info("-----------------------list{}",list);

        //根据阅读量排序查询(大家都在看)，获取10条数据
        ResponseVO<List<ArticlePo>> ranking = articleApi.pvLimitQuery(pageBeanVo);
        List<ArticlePo> rankingList = ranking.getData();

        //查询所有数据（根据浏览量），下架的除外，获取4条数据，包含图片（专家推荐）
        ResponseVO<List<ArticlePo>> res = articleApi.pvQueryContent();
        List<ArticlePo> articleData = res.getData();

        //分类
        List<SortPO> sortList = sortApi.totalQuery().getData();

        log.info("***************************sortList:{}",sortList);
        mv.addObject("sortList",sortList);
        mv.addObject("ranking",rankingList);
        mv.addObject("list",list);
        mv.addObject("rec",articleData);
        mv.addObject("logicUser",logicUser);
        return mv;
    }

    @GetMapping("/category/{category}")
    public ModelAndView categorysort(@PathVariable String category) throws UnsupportedEncodingException {

        UserPO logicUser = findByEmail();

        ModelAndView mav = new ModelAndView("article/category");
        ArticleSortNameQueryVo queryVo = new ArticleSortNameQueryVo();
        category = URLDecoder.decode(category,"utf-8");
        queryVo.setSortname(category);
        queryVo.setCurrentPage(1);
        queryVo.setPageSize(15);
        ResponseVO<List<ArticlePo>> responseVO = articleApi.sortNameQuery(queryVo);

        //文章（分类，推荐）
        List<ArticlePo> articleList = responseVO.getData();

        //计算该分类下的文章数量
        Integer count = articleApi.sortNameCount(category);
        //总页数
        Integer countPages = count%15==0 ? count/15 : ((count/15)+1);

        log.info("count ---------------------------{}",count);

        //相关推荐
        queryVo.setPageSize(10);
        List<ArticlePo> correlation = articleApi.sortNameQuery(queryVo).getData();

        log.info("********************************articleList ***{}",articleList);
        log.info("********************************countPages:{}",countPages);

        //其他看点
        queryVo.setPageSize(6);
        List<ArticlePo> anthers = articleApi.pvQuery().getData();

        //分类
        List<SortPO> sortList = sortApi.totalQuery().getData();

        mav.addObject("type","all");
        mav.addObject("current",1);
        mav.addObject("countPages",countPages);
        mav.addObject("correlation",correlation);//相关推荐
        mav.addObject("sortList",sortList);//分类（所有分类）
        mav.addObject("catelist",articleList);//页面主体部分数据（根据分类名称查询文章）
        mav.addObject("sortname",category);//分类名称
        mav.addObject("another",anthers);//其他看点
        mav.addObject("logicUser",logicUser);
        return mav;
    }

    @GetMapping("/category/{type}/{category}")
    public ModelAndView categorynewset( @PathVariable String type, @PathVariable String category) throws UnsupportedEncodingException {

        UserPO logicUser = findByEmail();

        category = URLDecoder.decode(category,"utf-8");

        ModelAndView mav = new ModelAndView("article/category");
        ArticleSortNameQueryVo queryVo = new ArticleSortNameQueryVo();
        queryVo.setSortname(category);
        queryVo.setCurrentPage(1);
        queryVo.setPageSize(15);

        log.info("------------------------------category:{}",category);
        log.info("------------------------------type:{}",type);

        ResponseVO<List<ArticlePo>> responseVO = null;
        //=  articleApi.newest(queryVo)
        if("host".equals(type)){
            log.info("热门------------------------------------------");
            responseVO =  articleApi.sortName(queryVo);//文章（分类，热门）
        }else if("newest".equals(type)){
            log.info("最新------------------------------------------");
            responseVO =  articleApi.newest(queryVo);//文章（分类，最新）
        }

        List<ArticlePo> articleList = responseVO.getData();

        log.info("------------------------------articleList:{}",articleList);

        //相关推荐
        queryVo.setPageSize(10);
        List<ArticlePo> correlation = articleApi.sortNameQuery(queryVo).getData();

        //其他看点
        //queryVo.setPageSize(6);
        List<ArticlePo> anthers = articleApi.pvQuery().getData();

        //分类
        List<SortPO> sortList = sortApi.totalQuery().getData();

        //计算该分类下的文章数量
        Integer count = articleApi.sortNameCount(category);

        log.info("count ---------------------------{}",count);

        //总页数
        Integer countPages = count%15==0?count/15:(count/15)+1;

        mav.addObject("current",1);
        mav.addObject("countPages",countPages);
        mav.addObject("type",type);
        mav.addObject("correlation",correlation);//相关推荐
        mav.addObject("sortList",sortList);//分类（所有分类）
        mav.addObject("catelist",articleList);//页面主体部分数据（根据分类名称查询文章）
        mav.addObject("sortname",category);//分类名称
        mav.addObject("another",anthers);//其他看点
        mav.addObject("logicUser",logicUser);
        return mav;
    }

    @GetMapping("/category/{type}/{category}/{currentPage}")
    public ModelAndView categorys( @PathVariable String type, @PathVariable String category, @PathVariable Integer currentPage) throws UnsupportedEncodingException {

        UserPO logicUser = findByEmail();

        ModelAndView mav = new ModelAndView("article/category");
        ArticleSortNameQueryVo queryVo = new ArticleSortNameQueryVo();
        category = URLDecoder.decode(category,"utf-8");
        queryVo.setSortname(category);
        queryVo.setCurrentPage(currentPage);
        queryVo.setPageSize(15);

        log.info("最新------------------------------category:{}",category);
        //articleApi.newest(queryVo)
        ResponseVO<List<ArticlePo>> responseVO =  null;

        if("host".equals(type)){
            responseVO =  articleApi.sortName(queryVo);//文章（分类，热门）
        }else if("newest".equals(type)){
            responseVO =  articleApi.newest(queryVo);//文章（分类，最新）
        }else if("all".equals(type)){
            responseVO =  articleApi.sortNameQuery(queryVo);//文章（分类，全部）
        }

        List<ArticlePo> articleList = responseVO.getData();

        //相关推荐
        queryVo.setCurrentPage(1);
        queryVo.setPageSize(10);
        List<ArticlePo> correlation = articleApi.sortNameQuery(queryVo).getData();

        log.info("********************************{}",correlation);

        //其他看点
        /*queryVo.setCurrentPage(1);
        queryVo.setPageSize(6);*/
        List<ArticlePo> anthers = articleApi.pvQuery().getData();

        //分类
        List<SortPO> sortList = sortApi.totalQuery().getData();

        //计算该分类下的文章数量
        Integer count = articleApi.sortNameCount(category);
        //总页数
        Integer countPages = count%15==0?count/15:(count/15)+1;

        mav.addObject("current",currentPage);
        mav.addObject("countPages",countPages);
        mav.addObject("type",type);
        mav.addObject("correlation",correlation);//相关推荐
        mav.addObject("sortList",sortList);//分类（所有分类）
        mav.addObject("catelist",articleList);//页面主体部分数据（根据分类名称查询文章）
        mav.addObject("sortname",category);//分类名称
        mav.addObject("another",anthers);//其他看点
        mav.addObject("logicUser",logicUser);
        return mav;
    }

    public UserPO findByEmail(){

        String email = (String) request.getSession().getAttribute("logicEmail");
        if(email != null){
            return userApi.findUserByEmail(email).getData();
        }

        log.info("email ============= {}",email);

        return null;
    }


}
